const fs = require('fs')
const path = require('path')

// 计算字数的函数
const calculateWordCount = (text) => {
  // 移除HTML标签
  const plainText = text.replace(/<[^>]*>/g, '')
  
  // 移除markdown语法（保留表格单元格文本）
  const cleanText = plainText
    .replace(/#{1,6}\s+/g, '') 
    .replace(/\*\*(.*?)\*\*/g, '$1') 
    .replace(/\*(.*?)\*/g, '$1') 
    .replace(/`(.*?)`/g, '$1') 
    .replace(/```[\s\S]*?```/g, '') 
    .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') 
    .replace(/!\[([^\]]*)\]\([^)]*\)/g, '') 
    .replace(/^\s*[-*+]\s+/gm, '') 
    .replace(/^\s*\d+\.\s+/gm, '') 
    .replace(/^\s*>\s+/gm, '') 
    // 保留表格内容：先去掉表格对齐分隔线，如 |---|:---:|---|
    .replace(/^\s*\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/gm, '')
    // 将表格行的起始竖线去掉
    .replace(/^\s*\|/gm, '')
    // 将其余竖线替换为空格，保留单元格文本
    .replace(/\|/g, ' ')
    // 分隔线
    .replace(/^\s*---\s*$/gm, '') 
    // 代码块标记
    .replace(/^\s*`{3,}.*$/gm, '') 
    .replace(/^\s*`.*$/gm, '') 
    .replace(/\n\s*\n/g, '\n') 
    .trim()

  // 中文
  const chineseChars = (cleanText.match(/[\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]/g) || []).length
  
  // 英文单词
  const englishWords = (cleanText.match(/[a-zA-Z]+/g) || []).length
  
  // 数字
  const digits = (cleanText.match(/[0-9]/g) || []).length
  
  // 总字符数（中文字符+英文单词+数字）
  const totalChars = chineseChars + englishWords + digits
  
  return {
    total: totalChars,
    chinese: chineseChars,
    englishWords: englishWords,
    digits: digits,
    formatted: totalChars >= 1000 ? `${(totalChars / 1000).toFixed(1)}K` : `${totalChars}`
  }
}

// 递归读取目录中的所有markdown文件
const readMarkdownFiles = (dir) => {
  const files = []
  
  const readDir = (currentDir) => {
    const items = fs.readdirSync(currentDir)
    
    for (const item of items) {
      const fullPath = path.join(currentDir, item)
      const stat = fs.statSync(fullPath)
      
      if (stat.isDirectory()) {
        // 跳过node_modules和.git目录
        if (item !== 'node_modules' && item !== '.git' && !item.startsWith('.')) {
          readDir(fullPath)
        }
      } else if (item.endsWith('.md')) {
        files.push(fullPath)
      }
    }
  }
  
  readDir(dir)
  return files
}

// 主函数
const main = () => {
  const srcDir = path.join(__dirname, '../src')
  const files = readMarkdownFiles(srcDir)
  
  let totalStats = {
    total: 0,
    chinese: 0,
    englishWords: 0,
    digits: 0,
    files: 0
  }
  
  
  for (const file of files) {
    try {
      const content = fs.readFileSync(file, 'utf-8')
      const stats = calculateWordCount(content)
      totalStats.total += stats.total
      totalStats.chinese += stats.chinese
      totalStats.englishWords += stats.englishWords
      totalStats.digits += stats.digits
      totalStats.files++
      
    } catch (error) {
      console.error(`❌ 读取文件失败: ${file}`, error.message)
    }
  }
  
  console.log('📊 统计结果:')
  console.log(`🔤 总字符数: ${totalStats.total.toLocaleString()}`)
  console.log(`📝 中文字符: ${totalStats.chinese.toLocaleString()}`)
  console.log(`🔤 英文单词: ${totalStats.englishWords.toLocaleString()}`)
  console.log(`🔢 数字字符: ${totalStats.digits.toLocaleString()}`)
}

// 如果直接运行此文件
if (require.main === module) {
  main()
}

module.exports = { calculateWordCount, readMarkdownFiles } 